package org.metasketch.graphics.loader;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import org.metasketch.graphics.BaseGraphic;
import org.metasketch.graphics.Diagram;
import org.metasketch.graphics.GraphicContainer;
import org.metasketch.graphics.GraphicLink;
import org.metasketch.graphics.GraphicNode;
import org.metasketch.model.CommonIdentified;

import com.thoughtworks.xstream.XStream;

public class DiagramFileHandler {

	private static XStream geXStream() {

		XStream xstream = new XStream();
		xstream.autodetectAnnotations(true);

		xstream.processAnnotations(CommonIdentified.class);
		xstream.processAnnotations(BaseGraphic.class);
		xstream.processAnnotations(GraphicContainer.class);
		xstream.processAnnotations(GraphicLink.class);
		xstream.processAnnotations(GraphicNode.class);
		xstream.processAnnotations(Diagram.class);

		return xstream;
	}

	public static Diagram read(String path) throws Throwable {

		XStream xstream = geXStream();

		FileReader reader = new FileReader(path);
		Diagram diagram = (Diagram) xstream.fromXML(reader);
		reader.close();

		return diagram;

	}

	public static void write(Diagram diagram, String path) throws Throwable {

		XStream xstream = geXStream();

		String completePath = path + "\\" + diagram.getId() + ".xml";
		
		File filePath = new File(completePath);

		if (!filePath.exists())
			filePath.createNewFile();

		FileWriter writer = new FileWriter(filePath);
		xstream.toXML(diagram, writer);
		writer.close();

	}

}
